package com.gmscosmo.janus.sendMessage;

import com.alibaba.fastjson.JSONObject;
import com.gmscosmo.janus.util.JanusLogUtil;
import com.gmscosmo.model.Event;
import com.gmscosmo.janus.netty.ConnectionManager;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author stephen.qiu
 */
@Component
public class WebSocketSender extends Sender {
    @Autowired
    ConnectionManager connectionManager;
    @Override
    public void sendEventToListener(String userId, JSONObject data) {
        if (userId == null) {
            janusLogUtil.log("sendEventToListener userId is null data "+ data,this.getClass(), JanusLogUtil.ERROR);
            return;
        }
        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(data.toJSONString());
        Channel channel = connectionManager.get(userId);
        if(channel!=null) {
            channel.writeAndFlush(textWebSocketFrame);
            janusLogUtil.log("sendEventToListener"+ data,this.getClass(), JanusLogUtil.ERROR);
        }else {
            janusLogUtil.log("user:"+ userId+"is not active",this.getClass(), JanusLogUtil.ERROR);
        }
    }

    @Override
    public void sendEvent(String userId, Event event) {
        if (userId == null) {
            janusLogUtil.log("sendEvent userId is null data "+ JSONObject.toJSONString(event),this.getClass(), JanusLogUtil.ERROR);
            return;
        }
        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(JSONObject.toJSONString(event));
        Channel channel = connectionManager.get(userId);
        if(channel!=null) {
            channel.writeAndFlush(textWebSocketFrame);
            janusLogUtil.log("sendEvent: "+ JSONObject.toJSONString(event),this.getClass(), JanusLogUtil.ERROR);
        }else {
            janusLogUtil.log("user:"+ userId+"is not active",this.getClass(), JanusLogUtil.ERROR);
        }
    }
}
